package org.soenea.doitall.domain.model.invite.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import org.dsrg.soenea.domain.DomainObjectCreationException;
import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;
import org.dsrg.soenea.domain.mapper.IdentityMap;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.model.group.GroupProxy;
import org.soenea.doitall.domain.model.group.IGroup;
import org.soenea.doitall.domain.model.invite.data.*;
import org.soenea.doitall.domain.model.invite.*;
import org.soenea.doitall.domain.model.user.UserProxy;

public class InviteInputMapper {

	public static List<Invite> findAll() throws MapperException {
		List<Invite> groups = new Vector<Invite>();
		try {
			ResultSet rs = InviteFinder.findAll();
			while (rs.next()) {
				groups.add(getInvite(rs));
			}
		} catch (SQLException e) {
			throw new MapperException(e);
		}
		return groups;
	}
	
	public static List<Invite> find(long userID) throws MapperException,
	DomainObjectNotFoundException {
		List<Invite> invites = new Vector<Invite>();
		try {
			ResultSet rs = InviteFinder.find(userID);
			while (rs.next()) {
				invites.add(getInvite(rs));
			}
		} catch (SQLException e) {
			throw new MapperException(e);
		}
		return invites;
	}
	
	public static Invite findInviteByInviteID(long inviteID) throws MapperException,
	DomainObjectNotFoundException {
	try {
		if (IdentityMap.has(inviteID, Invite.class))
			return IdentityMap.get(inviteID, Invite.class);
		
		ResultSet rs = InviteFinder.findInviteByInviteID(inviteID);
		if (rs.next()) {
			return getInvite(rs);
		} else {
			throw new DomainObjectNotFoundException("The username and password entered is not found!");
		}
	} catch (SQLException e) {
		throw new MapperException(e);
	    }
    }
	
	public static List<IInvite> find(IGroup group) throws SQLException, MapperException,DomainObjectCreationException{
		ResultSet rs = InviteFinder.findByGroupID(group.getId());
		List<IInvite> groups = new Vector<IInvite>();
		while (rs.next()) {
			groups.add(getInvite(rs));
		}
		return groups;
	}
	
	private static Invite getInvite(ResultSet rs) throws SQLException {
		Invite i = new Invite(rs.getLong("i.inviteID"), rs.getLong("i.version"), new UserProxy(rs.getLong("i.userIdInviter")), new UserProxy(rs.getLong("i.userIdInvited")), new GroupProxy(rs.getLong("i.groupID")),rs.getInt("i.status"));
		UoW.getCurrent().registerClean(i);
		return i;
	}
}
